//var baseURL="",
// var baseURL="http://10.10.2.102:3000",
var baseURL="http://120.25.227.185:9001",
	getReadDataURL = baseURL+"/reader/get_data",
	getBookListURL = baseURL+"/reader/book_chapter_capture",
	getTransURL = baseURL+"/translate",
	getUserInfoURL = baseURL+"/user/user_info",
	updateVocabularyURL = baseURL+"/user/update_vocabulary",
	updateVocabularyByPageURL = baseURL+"/user/update_vocabulary_by_page",
	getdata,
	article,
	unKnownWords,
	unKnownWordCn,
	articleWords,
	unKnownWordsOrigin,
	unKnownWordCnOrigin,
	unKnownWordsSize,
	articleWordsSize,
	lwc,
	// bookChapterCapture,
	book_name,
	chapter_size,
	content,
	chapter_count = 1,
	userInfo,
	$wordCount = $(".word_count"),
	$bookCont = $(".book_cont"),
	$transArea,
	$rightArea = $(".right");

var loadText = {
	
	getBookList : function(url){
		// bookChapterCapture={};
		$.ajax({
			type:"get",
			url:url,
			async: false,
			xhrFields: {
                      withCredentials: true
             },
			crossDomain:true,
			success:function(res){
				// loadText.setbookChapterCapture(res);
				bookChapterCapture = res;
				

			}
				
		})

	},
	getData : function(url,chapter_count0){
		var chapterName = bookChapterCapture["content"][0][book_name][chapter_count0];
		console.log(book_name);
		// console.log(content[0][book]);
		console.log(chapterName);
		$.ajax({
			type:"get",
			url:url,
			async: false,
			xhrFields: {
                      withCredentials: true
             },
			crossDomain:true,
			data : {book :book_name,chapter:chapterName},
			success:function(res){
				getdata = res;
			}				
		});
		
		var article0 = getdata.data;
		//article = article0.replace(/\n/g,"<br/>");
		article = "<div class='p_a_r_a'>&nbsp;&nbsp;&nbsp;&nbsp;" + article0.split("\n").join("</div><div class='p_a_r_a'>&nbsp;&nbsp;&nbsp;&nbsp;") + "</div>";
		console.log(article);
		articleWords = getdata.article_words;
		unKnownWords = getdata.unknow_words;
		// unKnownWordsOrigin = getdata0.unknow_words;
		unKnownWordsCn = getdata.unknown_words_cn;
		// unKnownWordsCnOrigin = getdata0.unknown_words_cn;
		articleWordsSize = getdata.article_words_size,
		unknownWordsSize = getdata.unknown_words_size,
		console.log(unKnownWords);

	},
	getUserInfo : function(url){
		$.ajax({
			type:"get",
			url:url,
			async: false,
			xhrFields: {
                      withCredentials: true
             },
			crossDomain:true,
			success:function(res){
				userInfo = res;
			}				
		});
	},
	updateVocabulary : function(url,type,word,word_id){
		console.log(type+","+word);
		$.ajax({
			type:"get",
			url:url,
			async: false,
			xhrFields: {
                      withCredentials: true
             },
			crossDomain:true,
			data : {type : type,word:word,word_id:word_id},
			success:function(res){
				// lwc = res.user_vocabulary_size;
				$wordCount.html(res.user_vocabulary_size);
			}				
		});
	},
	updateVocabularyByPage : function(url){
		$.ajax({
			type:"get",
			url:url,
			async: false,
			xhrFields: {
                      withCredentials: true
             },
			crossDomain:true,
			success:function(res){
				$wordCount.html(res.user_vocabulary_size);
			}
		});
	},
	dotWord : function(word_id,trans){
		$('[data-word_id="'+word_id+'"]').after('<span class="trans" data-trans_id='+word_id+'>'+trans+'</span><span class="dot" data-dot_id='+word_id+'></span>')
		$('[data-trans_id="'+word_id+'"]').each(function(){
			$(this).css({
				"width" : $(this).parent().width()*2,
				"left" : -0.5*($(this).parent().width())
			})
		})
		$("[data-dot_id="+word_id+"]").each(function(){
			$(this).css({
				"left":0.5*($(this).parent().width())
			})
		})
	},
	formatArticle : function(){
		var replacedText = article;
		$.each(articleWords,function(i){
			var text,reg,
				word = i,
				word_id = articleWords[i],
				word_length = word.length;
				text = replacedText;
				reg = new RegExp(word,"gi");

			replacedText = text.replace(reg,function(a,b){
			
				if((text[b-1]&&/[^a-zA-Z<=>_-]/.test(text[b-1])&&text[b+word_length]&&/[^a-zA-Z<=>_-]/.test(text[b+word_length])) || (!text[b-1]&&text[b+word_length]&&/[^a-zA-Z<=>_-]/.test(text[b+word_length])) || (!text[b+word_length]&&text[b-1]&&/[^a-zA-Z<=>_-]/.test(text[b-1])) || (!text[b-1]&&!text[b+word_length])){
					return '<div class="word_area"><span class="dot_word" data-word_id='+word_id+'>'+a+'</span></div>';
				}
				else{
					return a;
				}
			});
			
		});

		$bookCont.html(replacedText);
		$.each(unKnownWords,function(i){
			
			var word_id = unKnownWords[i],
			trans = unKnownWordsCn[i];
			loadText.dotWord(word_id,trans);
			
		});
		
		$(".dot_word").bind("click",function(){
			event.stopPropagation();
			var choose_easy,
				that = this,
				pos = $(this).offset(),
				word_id = $(this).data("word_id"),
				word = $(this).text().toLowerCase(),
				width = $(this).width(),
				height = $(this).height();
			if($('[data-trans_id="'+word_id+'"]').length){
				choose_easy = 1;
					
				$('[data-word_id="'+word_id+'"]').removeClass("word_difficult").addClass("word_easy");
			}
			else{
				choose_easy = 0;
				
				$('[data-word_id="'+word_id+'"]').removeClass("word_easy").addClass("word_difficult")
			}
			var getTransRes = loadText.getTrans(getTransURL,word);
			console.log("得翻译请求回来"+getTransRes.word);
			var trans = getTransRes.cn_trans;
			
			loadText.translation(getTransRes,choose_easy,pos.left,pos.top,word,word_id,width,height);
			if(choose_easy == 0){				
				loadText.dotWord(word_id,trans);
				$(".e_a_s_y").removeClass("choose_easy");
				$(".h_a_r_d").addClass("choose_hard")
			}
			else{
				$(".e_a_s_y").addClass("choose_easy");
				$(".h_a_r_d").removeClass("choose_hard");
				$("[data-trans_id="+word_id+"]").remove();
				$("[data-dot_id="+word_id+"]").remove();
			}
		})
	
		
	},
	getTrans : function(url,word){
		var getTransRes;
		$.ajax({
			type : "get",
			url : url,
			async: false,
			data : {word:word},
			success:function(res){
				getTransRes = res;				
			}				
		})
		return getTransRes;
	},
	translation : function(transobj,choose_easy,posX,posY,word,word_id,width,height){
	
		var if_choose_easy = choose_easy,
			enterTransArea = 0,
			trans = transobj.cn_trans;

		$(".wrap_container").append("<div class='trans_area'><div class='trans_area_word'>"+word+"</div><div class='cn_trans'>"+transobj.cn_trans+"</div><div class='choose_button'><span class='btn e_a_s_y'>Easy</span><span class='btn h_a_r_d'>Difficult</span></div></div>");
		console.log("添加翻译框成功");
		$transArea = $(".trans_area");
		$transArea.css({
			"left" : posX + 0.5*width-0.5*$transArea.width(),
			"top" : posY + height +8,
		});
		$(".e_a_s_y").click(function(){
			if_choose_easy = 1;
			console.log("点了easy");
			$(".e_a_s_y").addClass("choose_easy");
			$(".h_a_r_d").removeClass("choose_hard")

			if($('[data-trans_id="'+word_id+'"]').length){
				$("[data-trans_id="+word_id+"]").remove();
				$("[data-dot_id="+word_id+"]").remove();
			}
			
		});
		$(".h_a_r_d").click(function(){
			if_choose_easy = 0;
			$(".e_a_s_y").removeClass("choose_easy");
			$(".h_a_r_d").addClass("choose_hard");

			if($('[data-trans_id="'+word_id+'"]').length == 0 ){
				loadText.dotWord(word_id,trans);
			}

		});
		$transArea.mouseleave(function(){
			$(this).remove();
			console.log("移除翻译框");
			loadText.wordArrAndCount(word_id,trans,if_choose_easy,word);
		});
		$transArea.mouseenter(function(){
			enterTransArea = 1;
			console.log("鼠标进入翻译框"+enterTransArea);

		});
		

		$('[data-word_id="'+word_id+'"]').mouseleave(function(){
			setTimeout(function(){				
				if(enterTransArea == 0){
					$transArea.remove();
					console.log("移除翻译框");
					loadText.wordArrAndCount(word_id,trans,if_choose_easy,word);
					console.log("鼠标离开单词,且短时间内没有进入翻译框")
				}
			},500)
			
		})


	},
	wordArrAndCount : function(word_id,trans,if_choose_easy,word){
		console.log("单词"+word);
		// 若没点easy按钮，即默认difficult
		if(if_choose_easy == 0){
				if(articleWords[word]){
					if(!unKnownWords[word]){
						loadText.updateVocabulary(updateVocabularyURL,"remove",word,word_id);
						console.log("变为difficult");
						// lwc--;
						unKnownWords[word] = word_id;
						unKnownWordsCn[word] = trans;
						// $wordCount.html(lwc);
					}					
				}
				else{
					console.log("文章单词里没有")
				}
			}
		else{
			if(articleWords[word]){
				if(unKnownWords[word]){
					
					loadText.updateVocabulary(updateVocabularyURL,"add",word,word_id);					
					// lwc++;
					delete unKnownWords[word];
					delete unKnownWordsCn[word];
					// $wordCount.html(lwc);
				}
			}
			
		}
	},
	transDisplay : function(){
		$rightArea.bind("mouseenter", function(){ 
			$(".trans").fadeIn(200,function(){
				setTimeout(function () {
					$(".trans").fadeOut(500);
				}, 500)
			})

		
		});
	},
	lastPage : function(){
		var lastPageAction = function () {
			event.stopPropagation;
			console.log("点上一页");
			if(chapter_count >= 2 ){
				chapter_count--;
				loadText.getPage(chapter_count-1);
				$(".current_page_num").html(chapter_count);
				loadText.updateVocabularyByPage(updateVocabularyByPageURL);
			}
			console.log(chapter_count);
		};
		$(".last_page").click(function () {
			lastPageAction();
		});
		$("body").keydown(function (event) {
			if (event.keyCode == 37) {
				lastPageAction();
			}

		});

	},
	nextPage : function(){
		var nextPageAction = function () {
			event.stopPropagation;
			console.log("点下一页");
			if(chapter_count < chapter_size){
				chapter_count++;
				loadText.getPage(chapter_count-1);
				$(".current_page_num").html(chapter_count);
				loadText.updateVocabularyByPage(updateVocabularyByPageURL);
			}
		};
		$(".next_page").click(function () {
			nextPageAction();
		});
		$("body").keydown(function (event) {
			if (event.keyCode == 39) {
				nextPageAction();
			}
		});

	},
	getPage : function(chapter_count) {
		loadText.getData(getReadDataURL,chapter_count);			
		loadText.formatArticle();		
		
		
	},
	init : function(){
		$(".center").css({"height":$(window).height()-30});
		$(window).resize(function(){
			$(".center").css({"height":$(window).height()-30});
		});
		loadText.getUserInfo(getUserInfoURL);
		console.log(userInfo);
		$wordCount.html(userInfo.user_vocabulary_size);
		loadText.getBookList(getBookListURL);
		console.log("得到单子"+bookChapterCapture);
		book_name = bookChapterCapture["book_list"][0];
		chapter_size = bookChapterCapture["content"][0][book_name].length;
		if(userInfo.process){
			chapter_count = bookChapterCapture["content"][0][book_name].indexOf(userInfo.process)+1;
		}
		loadText.getPage(chapter_count-1);

		$(".current_page_num").html(chapter_count);
		$(".total_page_num").html(chapter_size);
		loadText.transDisplay();
		loadText.nextPage();
		loadText.lastPage();
		$(".page_nav").css({"display":"block"});
	}
};
loadText.init();



